home *** CD-ROM | disk | FTP | other *** search
- Path: news.ccs.queensu.ca!news
- From: Wintermute <3mal5@qlink.queensu.ca>
- Newsgroups: comp.lang.c++
- Subject: Re: Array declaration
- Date: Thu, 04 Apr 1996 07:29:27 -0500
- Organization: System Infinity
- Message-ID: <3163C0A7.2BBF@qlink.queensu.ca>
- References: <4jvo2g$mp2@hermes.is.co.za>
- NNTP-Posting-Host: qlink.queensu.ca
- Mime-Version: 1.0
- Content-Type: text/plain; charset=us-ascii
- Content-Transfer-Encoding: 7bit
- X-Mailer: Mozilla 2.0 (X11; I; qlink 5.4 sun4d)
-
- Janine Prinsloo wrote:
- > I declared the following array: dat[7][2048]
- > In the program I made the stupid mistake of using loops going from 1 to 7
- > and from 1 to 2048 instead of 0 to 6 and 0 to 2047. What I don't understand
- > is that the program ran fine for a number of times (the program is repeatedly
- > run by a batch program) before an error occurred.
- >
- > I would like to know why an error didn't occur immediately the first time
- > the program was run.
- >
- > Janine
-
- C/++ offer no bounds checking on array accesses, whatsoever. The array variable is
- merely a pointer to a byte in memory. The index is merely a value that is added to
- the value of the array variable, which is the address of the first element of the
- array.
-
- Suppose you declare an array of eight characters:
-
- char dat[8];
-
- dat is simply a 4-byte pointer to char, and its value is the memory address of the
- first byte of the eight that are allocated.
-
- You can access those eight bytes using dat[0] to dat[7], but you could also use
- dat[-438] or dat[23422]. Your compiler may give you a warning if it is good, but
- there is nothing wrong with the code.
-
- The problem is, you have no idea what is in the bytes that are not of the original 8
- you allocated. You could be changing a global variable, or a return address, or
- even something in the operating system, probably wrecking your memory and producing
- a segmentation fault.
-
- You can also do pointer arithmetic on dat, or cast it, but I digress.
-
- The fix to this error is to ensure that you are ALWAYS within the bounds of your
- array. You can do this by declaring consts that are the size of your array, and
- using them to limit indexing into the array, as in for statements.
-
- Hope this helps.
-
- --
- Wintermute <3mal5@qlink.queensu.ca> <http://qlink.queensu.ca/~3mal5/>
-
- "If I really knew how to write, I could write something that someone
- could read and it would kill them." - william s. burroughs
-